<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }
  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }
  .rj-cell.note label{
    float: left;
  }
  .rj-cell.note span{
    width: 80%;
    display: inline-block;
  }
  .weui-cells {
    margin-top: 0;
  }
  .weui-cells_form {
    background: #fbfbfb;
  }
  .weui-cell {
    background: #fff;
  }
  #acts span {
    font-size: 14px;
  }
  .halfbtn {
    display: inline-block;
    width: 49%;
  }
  .weui-label {
    text-align: left;
  }

  .weui_uploader_input_wrp {
    float: left;
    position: relative;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 77px;
    height: 77px;
    border: 1px solid #D9D9D9;
  }
  .weui_uploader_hd {
    padding-top: 0;
    padding-right: 0;
    padding-left: 0;
  }
  .weui_uploader_input_wrp:before {
    width: 2px;
    height: 39.5px;
  }
  .weui_uploader_input_wrp:before, .weui_uploader_input_wrp:after {
    content: " ";
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    background-color: #D9D9D9;
  }
  .weui_uploader_input {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  }
  .weui_uploader_input_wrp:after {
    width: 39.5px;
    height: 2px;
  }
  .weui_uploader_bd {
    overflow: hidden;
  }
  .weui_cell {
    padding: 10px 15px;
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
  }
  .sellfsure >>> .weui-uploader_files {
    list-style: none;
    overflow-y: hidden;
  }
  .sellfsure >>> .weui-uploader_file {
    float: left;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 79px;
    background: no-repeat 50%;
    background-size: cover;
  }
  .help {
    position: absolute;
    right: 0;
    top: 5px;
    font-size: 12px;
    color: #bbb;
  }
</style>
<template>
  <div class="sellfsure">
    <div class="rj-wrap">
      {{title}}
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
      <form action="" method="post" id="formid">
        <input type="hidden" name="entity.guid" :value="baseInfo.guid" />
        <input type="hidden" name="entity.amount" :value="baseInfo.amount" />
        <input type="hidden" name="entity.unloadcount" :value="baseInfo.unloadcount" />
        <div class="cellgroup">
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">订单编号</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" readonly :value="baseInfo.sellcode" name="">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">申请人</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" readonly  type="text"  name="" :value="baseInfo.applyname" style="width: 30%;display:inline-block;">
              <input class="weui-input" readonly  type="text"  name="" :value="baseInfo.depname" style="width: 67%; display:inline-block;">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">客户</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" readonly  type="text"  name="" :value="baseInfo.customername">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">备注</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" name="" readonly :value="baseInfo.remarks">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">订单金额</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" name="entity.amount" readonly :value="baseInfo.finalamount">
            </div>
          </div>
          <div class="weui-cell"v-if="baseInfo.deductamount != ''">
            <div class="weui-cell__hd"><label class="weui-label">扣款金额</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" name="entity.amount" readonly v-model="baseInfo.deductamount">
            </div>
          </div>
          <div class="weui-cell" v-if="baseInfo.settletype == 1">
            <div class="weui-cell__hd"><label class="weui-label">结算件数</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" name="entity.finalcount" readonly :value="baseInfo.finalcount" style="color: red;">
            </div>
          </div>
          <div class="weui-cell" v-if="baseInfo.settletype == 1">
            <div class="weui-cell__hd"><label class="weui-label">赠送件数</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" name="entity.handselcount" readonly :value="baseInfo.handselcount">
            </div>
          </div>
              <input class="weui-input" type="hidden" name="entity.finalweight" v-model="finalWeight" @change="editFinalWei($event)" style="color: red;">
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">结算金额({{baseInfo.currency == 2 ? '美元' : '元'}})</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="number" ref="finalamount" name="entity.finalamount" :readonly="!canEdit" v-model="finalAmount" style="color: red;">
              <p v-show="baseInfo.settletype == 2 || baseInfo.isdiscount == 1" class="help" @click="editAmount">调整金额？</p>
            </div>
          </div>
          <!--          <div class="weui-cell">-->
          <!--            <div class="weui-cell__hd"><label class="weui-label">创建时间</label></div>-->
          <!--            <div class="weui-cell__bd">-->
          <!--              <input class="weui-input" readonly type="text" name="" :value="baseInfo.createtime">-->
          <!--            </div>-->
          <!--          </div>-->
          <SellFinalSureItem v-for="(item, index) in allItems" :key="item.guid" :settletype="baseInfo.settletype" :concessiontype="baseInfo.concessiontype" :deliverytype="baseInfo.deliverytype" :quitSRType="baseInfo.quitSRType" :itemdata="item" :itemindex="index" :packindex="computeBasic(index)" @getFinal="doGetFinal"></SellFinalSureItem>
          <div ref="actHtml" class="fixcont">
            <div class="weui-cells weui-cells_form">
              <div class="weui-cell">
                <div class="weui-cell__bd">
                  <textarea class="weui-textarea" v-model="opinion" name="opinion" placeholder="请输备注内容" rows="3"></textarea>
                </div>
              </div>
            </div>
            <div class="weui_cell">
              <div class="weui_cell_bd weui_cell_primary">
                <div class="weui_uploader">
                  <div class="weui_uploader_hd weui_cell" style="padding-left: 0;">
                    <div class="weui_cell_bd weui_cell_primary" id="outstore">单据上传</div>
                    <div class="weui_cell_ft" id=""></div>
                  </div>
                  <div class="weui_uploader_bd">
                    <ul class="weui-uploader_files" id="images">
                      <li class="weui-uploader_file" v-for="(img, index) in images.serverId" :id="img"  @click=del(img) ><img :src="images.srcStr[index]" width="85" /></li>
                    </ul>
                    <div class="weui_uploader_input_wrp">
                      <input type="button" id="selectImage"  class="weui_uploader_input" >
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="weui-btn-area">
              <a class="weui-btn weui-btn_primary halfbtn subbtn" href="javascript:" @click="postForm">确定</a>
<!--              <a class="weui-btn weui-btn_primary halfbtn" href="javascript:" @click="backIt">退补货</a>-->
<!--              <a class="weui-btn weui-btn_primary halfbtn"  href="javascript:" @click="backStroom" id="sub">退回库房</a>-->
              <a class="weui-btn weui-btn_primary halfbtn"  href="javascript:" @click="$router.back(-1)" id="sub">返回</a>
            </div>
          </div>
        </div>
      </form>
    </div>
    <div id="bmlogs">
      <SalesOperationLogs2 :nodeid="nodeid" :orderid="id" :srguid="baseInfo.storermguid" :departid="baseInfo.depguid"></SalesOperationLogs2>
    </div>
  </div>
</template>

<script>
  import wx from 'weixin-js-sdk';
  import SellFinalSureItem from "./SellFinalSureItem";
  import SalesOperationLogs2 from '../common/SalesOperationLogs2'

  export default {
    name: 'SellFinalSure',
    data () {
      return {
        id: '',
        baseInfo: {},
        wxParams: {},
        nodeid: '',
        annex: '',
        title: '',
        images: {
          serverId: [],
          srcStr: [],
        },
        finalCount: '',
        finalWeight: '',
        finalAmount: '',
        amount: '', //总扣前金额
        opinion: '',
        settlerate: '',
        canEdit: false,
        tempFinalAmt: '',
        showEditBtn: true,
        backStrNodeid: '',
        allItems: '',
        tempFinalWei: ''
      }
    },
    components: {SellFinalSureItem, SalesOperationLogs2},
    mounted () {
      //提交操作定位到页面底部
      //$('#bmlogs').css('margin-bottom', this.$refs.actHtml.offsetHeight)

      let that = this;

      this.id = this.$route.query.guid;
      this.nodeid = this.$route.query.nodeid;
      this.annex = this.$route.query.annex;
      this.title = this.$route.query.title;
      this.backStrNodeid = this.$route.query.backStrNodeid;
      this.getBaseInfo(this.id, this);
      this.getSettlementInfo();
    },
    watch: {
    },
    methods: {
      editFinalWei: function(val) {
        if (val.target.value < this.tempFinalWei - 1 || val.target.value > this.tempFinalWei + 1) {
          this.toastText('结算重量有误');
          this.finalWeight = this.tempFinalWei;
        }
      },
      computeBasic: function(index) {
        let no = 0;
        let aitems = this.baseInfo.spitems.concat(this.baseInfo.items);
        aitems.forEach((item, i) => {
          if (i < index) {
            if (item.sellitems != undefined) {
              no += item.sellitems.length;
            } else {
              no += 1;
            }
          }
        })
        return no;
      },
      wxConfig: function(wxParams) {
        wx.config({
          debug: false,            // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: wxParams.appid,    // 必填，公众号的唯一标识
          timestamp: wxParams.timestamp,  // 必填，生成签名的时间戳
          nonceStr: wxParams.nonceStr, // 必填，生成签名的随机串
          signature: wxParams.signature,// 必填，签名
          jsApiList: ['scanQRCode', 'chooseImage', 'uploadImage'] // 必填，需要使用的JS接口列表
        });
      },
      wxUoloadImage: function(that) {
        let cthis = this;
        //wx.ready(function(){
        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        document.querySelector('#selectImage').onclick = function () {
          wx.chooseImage({
            success: function (res) {
              $(function(){
                $.each( res.localIds, function(i, n){
                  wx.uploadImage({
                    localId: n,
                    isShowProgressTips: 1,
                    success: function (res) {
                      if (that.checkCore() == 'ios') {
                        wx.getLocalImgData({
                          localId: n, // 图片的localID
                          success: function (res2) {
                            cthis.$nextTick(function () {
                              cthis.images.srcStr.push(res2.localData);
                            })
                          }
                        });
                      } else {
                        cthis.$nextTick(function () {
                          cthis.images.srcStr.push(n);
                        })
                      }

                      cthis.images.serverId.push(res.serverId);
                    },
                    fail: function (res) {
                      $.alert(JSON.stringify(res));
                    }
                  });
                });
              });
            }
          });
        };
        //});

      },
      del: function (id){
        let cthis = this;
        $.actions({
          actions: [{
            text: "删除",
            onClick: function() {
              $.confirm("确定删除?", function() {
                //点击确认后的回调函数
                //删掉id
                var ids = cthis.images.serverId;
                var a =  ids.indexOf(id);
                cthis.$nextTick(function () {
                  cthis.images.serverId.splice(a,1);
                  cthis.images.srcStr.splice(a,1);
                })
                //$("#"+id).hide();
              }, function() {
                //点击取消后的回调函数
              });
            }
          }
          ]
        });
      },
      checkCore:function() {
        var u = navigator.userAgent;
        //var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;//g
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);   //ios终端
        if (isIOS) {
          return 'ios';
        } else  {
          return 'android';
        }
      },
      getBaseInfo: function(id, that) {
        this.axios({
          method: 'post',
          url: '/sales/Sellform!getUpImagInfo.action',
          params: {sellformid: id, url: location.href.split("#")[0]}
        }).then(response => {
          if (response.status == 200) {
            // this.baseInfo = response.data.baseInfo;
            let wxParams = response.data.params;
            //配置微信公众号参数
            this.wxConfig(response.data.params);
            //上传
            this.wxUoloadImage(that);
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
            //不不设置提示
          } else {
            this.toastError('系统错误' + response.data.msg);
          }
        });
      },
      getSettlementInfo: function() {
        this.axios({
          method: 'post',
          url: '/sales/Sellform!getSettlementInfo.action',
          params: {guid: this.id}
        }).then(response => {
          if (response.data.msg == 'success') {
            this.baseInfo = response.data.sellform;
            this.allItems = this.baseInfo.spitems.concat(this.baseInfo.items);
            //this.finalCount = this.baseInfo.finalcount;
            this.finalAmount = this.toFix2(this.baseInfo.finalamount - parseFloat(this.baseInfo.deductamount));
            if (this.baseInfo.settletype == 1) {
              this.amount = this.toFix2(this.baseInfo.amount);
            }
            //结算金额浮动比例
            this.settlerate = response.data.settlerate;
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
            //不不设置提示
          } else {
            this.toastError('系统错误');
          }
        });
      },
      editAmount: function() {
        this.tempFinalAmt = this.finalAmount;
        this.canEdit = true;
        // this.showEditBtn = false;
        this.$refs.finalamount.focus();
      },
      doGetFinal: function(type = 1) {
        let finalAmount = 0;
        let finalCount = 0;
        let finalWeight = 0;
        let amount = 0;

        for (let i=0; i<this.baseInfo.items.length + this.baseInfo.spitems.length; i++) {
          let itemWei = $('.weight').eq(i).val() != '' ? $('.weight').eq(i).val() :  0;
          let handselWei = $('.handselweight').eq(i).val() != '' && $('.handselweight').eq(i).val() != undefined ? $('.handselweight').eq(i).val() :  0;

          if (this.baseInfo.settletype == 1) {
            finalCount += parseInt($('.count').eq(i).val());
          } else if (this.baseInfo.settletype == 2) {
            finalWeight += parseFloat(itemWei) - parseFloat(handselWei);
            amount += parseFloat(itemWei) * parseFloat($('.oitem').eq(i).data('price'));
          }
          let discount = $('.discount').eq(i).val() != '' ? parseFloat($('.discount').eq(i).val()) : 0;
          finalAmount += parseFloat(itemWei) * parseFloat($('.oitem').eq(i).data('price')) * (1 - discount / 100);
        }
        //this.finalCount = finalCount;
        this.amount = this.toFix2(amount);
        //非首次进入赋值
        if (type == 1) {
          this.finalWeight = this.toFix6(finalWeight);
        }
        this.tempFinalWei = this.toFix6(finalWeight);
        this.finalAmount = this.baseInfo.deductamount != '' ? this.toFix2(finalAmount - parseFloat(this.baseInfo.deductamount)) : this.toFix2(finalAmount);
      },
      checkMaxDeduct: function() {
        let status = false;
        for (let i=0; i < $('.discount').length; i++) {
          if (parseFloat($('.discount').val()) > this.baseInfo.maxdeduct) {
            status = true;
            break;
          }
        }
        return status;
      },
      backStroom: function() {
        let that = this;
        $.confirm("确定要退回到库房?", function() {
          //防止重复提交
          $('.subbtn').attr("disabled",true).css("pointer-events","none");
          //显示提交状态
          $.showLoading("正在提交");

          let postData = {};
          postData.imgids = that.images.serverId.join(',');
          postData.sellformid = that.id;
          postData.opinion = $('#opinion').val() != '' ? $('#opinion').val() : '同意';
          postData.nodeid = that.backStrNodeid;
          //postData.status = that.status;
          that.axios({
            method: 'post',
            url: '/sales/Sellform!approvalBack.action',
            params: postData
          }).then(response => {
            //恢复提交按钮可点击
            $('.subbtn').attr('disabled', false).css("pointer-events","auto");
            //关闭提交状态
            $.hideLoading();

            if (response.data.msg == 'success') {
              that.toastSuccess('提交成功!');
              that.$router.push({name: 'Sellform', query:{stat: that.status}});
            } else if (response.data.msg == 'canotRefuse') {
              that.toastText('不允许退回，需删除子订单！');
            } else if (response.data.msg == 'canotopt') {
              that.toastText('不允许的操作！');
            } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
              //不不设置提示
            } else {
              that.toastError('系统错误');
            }
          }).catch(function (error) {
            //恢复提交按钮可点击
            $('.subbtn').attr('disabled', false).css("pointer-events","auto");
            //关闭提交状态
            $.hideLoading();
            that.toastError('系统错误');
          });
        }, function() {
          //点击取消后的回调函数
        });
      },
      postForm: function () {
        let that = this;
        //canEdit 点击调整金额按钮后为true，执行西面两条判断
        // if (this.canEdit && this.settlerate == 1 && this.finalAmount != Math.round(this.tempFinalAmt) && this.finalAmount != this.tempFinalAmt) {
        //   this.toastText('结算金额的修改只允许四舍五入取整！');
        //   return false;
        // }
        // if (this.canEdit && this.settlerate != 0 && this.settlerate != 1 && (this.finalAmount < this.tempFinalAmt * (1-this.settlerate) || this.finalAmount > this.tempFinalAmt * (1+this.settlerate))) {
        //   this.toastText(`根据系统设定的浮动率:${this.settlerate * 100}%，结算金额不能超出区间:${this.tempFinalAmt * (1-this.settlerate)} -- ${this.tempFinalAmt * (1+this.settlerate)}`);
        //   return false;
        // }

        if (this.annex.indexOf('whout') > -1 && this.images.serverId.length == 0) {
          this.toastText('单据不能为空！');
          return false;
        }
        if (!this.checkEmy('weight')) {
          this.toastText('重量有误！');
          return false;
        } else if (!this.checkEmy('room')) {
          this.toastText('库间有误！');
          return false;
        } else if (this.checkMaxDeduct()) {
          this.toastText('扣杂率超出订单最大扣款率！');
          return false;
        }
        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

        let postData = {};
        postData = this.serialize2Obj($("#formid").serializeArray());
        postData.nodeid = this.nodeid;
        postData.imgids = this.images.serverId.join(',');
        postData.opinion = this.opinion;
        this.axios({
          method: 'post',
          url: '/sales/Sellform!confirmSettle.action',
          params: postData
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

          if (response.data.msg == 'success') {
            this.toastSuccess('操作成功!');
            this.$router.push({name: 'Sellform'});
          } else if (response.data.msg == 'canotopt') {
            this.toastText('不允许的操作！');
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
            //不不设置提示
          } else {
            this.toastError('系统错误');
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });
      },
      toFix2: function(num) {
        return Math.round(num * 100) / 100;
      },
      openLogs: function() {
        this.$router.push({name: 'SalesOperationLogs2', query: {orderid: this.id, srguid: this.baseInfo.storermguid, departid: this.baseInfo.depguid}});
      },
      backIt: function () {
        this.$router.push({name: 'AddBackinfo', query: {guid: this.id}});
      }
    }
  }
</script>
